<script setup lang='ts'>
import type { PlusColumn } from 'plus-pro-components'
import { useApplySave, applyShow, useGetCascade } from '@fl/api/add-elevator-api'
import { SubmitBtn } from '@fl/components'
import { cloneDeep } from 'lodash-es'
import type { applyEditParam, cascadeParam } from '@fl/api/add-elevator-api/model/apply-model'
import { number } from 'echarts'

const visible = defineModel<boolean>('visible', { required: true })
const id = defineModel<string>('id', { required: true })

const formRef = ref()
const title = ref<string>('录入申请')

const initialState = {
    areaCode: '',
    areaName: '',
    streetCode: '',
    streetName: '',
    communityCode: '',
    communityName: '',
    projectId: '',
    projectName: '',
    buildingId: '',
    building: '',
    unitId: '',
    unit: '',
    num: undefined,
}
const state = ref<applyEditParam>(cloneDeep(initialState))

const isLoading = ref<boolean>(false)
const isShowProjectId = ref<boolean>(false) // 输入小区时，还需输入小区编码

// 级联选择
const initialParams = {
    targetLabel: '',
    areaCode: '',
    streetCode: '',
    communityCode: '',
    projectName: '',
    building: '',
    unit: '',
    time: undefined, // 刷新用，每次选择后都调用接口
}
const areaParams = ref<cascadeParam>(cloneDeep(initialParams))
const streetParams = ref<cascadeParam>(cloneDeep(initialParams))
const communityParams = ref<cascadeParam>(cloneDeep(initialParams))
const projectParams = ref<cascadeParam>(cloneDeep(initialParams))
const buildingParams = ref<cascadeParam>(cloneDeep(initialParams))
const unitParams = ref<cascadeParam>(cloneDeep(initialParams))

const isProjectFocus = ref<boolean>(false)
const isBuildingFocus = ref<boolean>(false)
const isUnitFocus = ref<boolean>(false)

areaParams.value.targetLabel = 'area'

// 详情
function getApplyShow() {
    isLoading.value = true
    applyShow(id.value).then(res => {
        title.value = '编辑申请'
        state.value = res
        state.value.buildingId = state.value.building // 第3.4级没返id
        state.value.unitId = state.value.unit
        // 查街道
        streetParams.value.targetLabel = 'street'
        streetParams.value.areaCode = state.value.areaCode
        // 查社区
        communityParams.value.targetLabel = 'community'
        communityParams.value.streetCode = state.value.streetCode
        // 查小区
        projectParams.value.targetLabel = 'project'
        projectParams.value.communityCode = state.value.communityCode
        // 查栋
        buildingParams.value.targetLabel = 'building'
        buildingParams.value.projectId = state.value.projectName
        // 查单元
        unitParams.value.targetLabel = 'unit'
        unitParams.value.building = state.value.building

        isLoading.value = false
    }).catch(() => {
        isLoading.value = false
    })
}
watchEffect(() => {
    if (id.value) {
        getApplyShow()
    }
})

watch(() => visible.value, () => {
    if(visible.value) {
        reset()
    }
})

// 下拉框：过滤数据
const areaOptions = ref<any>()
const streetOptions = ref<any>()
const communityOptions = ref<any>()
const projectOptions = ref<any>()
const buildingOptions = ref<any>()
const unitOptions = ref<any>()
// 下拉框：原数据
const projectOriginOptions = ref<any>([])
const buildingOriginOptions = ref<any>([])
const unitOriginOptions = ref<any>([])

const { data: areaList } = useGetCascade(areaParams)
const { data: streetList } = useGetCascade(streetParams)
const { data: communityList } = useGetCascade(communityParams)
const { data: projectList } = useGetCascade(projectParams)
const { data: buildingList } = useGetCascade(buildingParams)
const { data: unitList } = useGetCascade(unitParams)

watchEffect(() => {
    if (areaList.value) {
        areaOptions.value = cloneDeep(areaList.value)
    }
    if (streetList.value) {
        streetOptions.value = cloneDeep(streetList.value)
    }
    if (communityList.value) {
        communityOptions.value = cloneDeep(communityList.value)
    }
    if (projectList.value) {
        projectOptions.value = cloneDeep(projectList.value)
        projectOriginOptions.value = cloneDeep(projectList.value)
    }
    if (buildingList.value) {
        buildingOptions.value = cloneDeep(buildingList.value)
        buildingOriginOptions.value = cloneDeep(buildingList.value)
    }
    if (unitList.value) {
        unitOptions.value = cloneDeep(unitList.value)
        unitOriginOptions.value = cloneDeep(unitList.value)
    }
})

const isStreetDisabeld = computed(() => {
    return !state.value.areaCode
})

const isCommunityDisabeld = computed(() => {
    return isStreetDisabeld.value  || !state.value.streetCode
})

const isProjectDisabeld = computed(() => {
    return isCommunityDisabeld.value || !state.value.communityCode
})
const isBuildingDisabeld = computed(() => {
    return isProjectDisabeld.value || !state.value.projectName
})
const isUnitDisabeld = computed(() => {
    return isBuildingDisabeld.value || !state.value.building
})

// 清空街道
function clearStreet() {
    state.value.streetCode = ''
    state.value.streetName = ''
    clearCommunity()
}

// 清空社区
function clearCommunity() {
    state.value.communityCode = ''
    state.value.communityName = ''
    clearProject()
}

// 清空小区
function clearProject() {
    state.value.projectId = ''
    state.value.projectName = ''
    clearBuilding()
}

// 清空栋
function clearBuilding() {
    state.value.buildingId = ''
    state.value.building = ''
    buildingOptions.value = []
    clearUnit()
}

// 清空单元
function clearUnit() {
    state.value.unitId = ''
    state.value.unit = ''
    unitOptions.value = []
}

//
function clickDialog() {
    projectBlur()
    buildingBlur()
    unitBlur()
}

// 1.选择区
function areaChange() {
    //清空
    state.value.streetCode = ''
    state.value.communityCode = ''
    clearStreet()

    const target = areaOptions.value.find((v: any) => v.value === state.value.areaCode)
    state.value.areaName = target.label
    streetParams.value.targetLabel = 'street'
    streetParams.value.areaCode = state.value.areaCode
    streetParams.value.time = new Date().getTime()
    // console.log('streetParams.value', streetParams.value)
}

// 2.街道选择
function streetChange() {
    //清空
    state.value.communityCode = ''
    // state.value.projectName = '' // ?
    clearCommunity()

    const target = streetOptions.value.find((v: any) => v.value === state.value.streetCode)
    state.value.streetName = target.label
    communityParams.value.targetLabel = 'community'
    communityParams.value.streetCode = state.value.streetCode
    communityParams.value.time = new Date().getTime()
    // console.log('communityParams.value', streetParams.value)
}

// 3.社区选择
function communityChange() {
    //清空
    state.value.projectId = ''
    // state.value.projectName = '' // ?
    clearProject()

    const target = communityOptions.value.find((v: any) => v.value === state.value.communityCode)
    state.value.communityName = target.label
    projectParams.value.targetLabel = 'project'
    projectParams.value.communityCode = state.value.communityCode
    projectParams.value.time = new Date().getTime()
    // console.log('projectParams.value', streetParams.value)
}

// 4.小区选择
function projectFocus() {
    isProjectFocus.value = true
    isBuildingFocus.value = false
    isUnitFocus.value = false
}
function projectBlur() {
    isProjectFocus.value = false
}
function chooseProject(item) {
    state.value.projectName = item.label
    state.value.projectId = item.value
    isShowProjectId.value = false
    projectBlur()
    buildingParams.value.targetLabel = 'building'
    buildingParams.value.projectId = state.value.projectId
    buildingParams.value.time = new Date().getTime()
    //清空
    clearBuilding()
}
function projectInput() {
    if(!state.value.projectName) {
        clearProject()
    } else {
        isShowProjectId.value = true
        state.value.projectId = ''
        clearBuilding()
    }
    projectOptions.value = projectOriginOptions.value.reduce((pre, cur) => {
        // state.value.projectName && 
        if (cur.label.indexOf(state.value.projectName) > -1) {
            pre.push(cur)
        }
        return pre
    }, [])
    // 无匹配数据，
    if(projectOptions.value.length === 0) {
        buildingOptions.value = []
        unitOptions.value = []
    }
}

// 5.栋选择
function buildingFocus() {
    isProjectFocus.value = false
    isBuildingFocus.value = true
    isUnitFocus.value = false
}
function buildingBlur() {
    isBuildingFocus.value = false
}
function chooseBuilding(item) {
    state.value.building = item.label
    state.value.buildingId = item.value
    buildingBlur()
    // unitParams.value = cloneDeep(initialParams)
    unitParams.value.targetLabel = 'unit'
    unitParams.value.building = state.value.building
    unitParams.value.time = new Date().getTime()
    //清空
    clearUnit()
}
function buildingInput() {
    if(!state.value.building) {
        clearBuilding()
    } else {
        clearUnit()
    }
    if(!state.value.projectId || !buildingOriginOptions.value) return
    buildingOptions.value = buildingOriginOptions.value.reduce((pre, cur) => {
        if (cur.label.indexOf(state.value.building) > -1) {
            pre.push(cur)
        }
        return pre
    }, [])
}

// 6.单元选择
function unitFocus() {
    isUnitFocus.value = true
}
function unitBlur() {
    isUnitFocus.value = false
}
function chooseUnit(item) {
    state.value.unit = item.label
    state.value.unitId = item.value
    unitBlur()
}
function unitInput() {
    if(!state.value.buildingId || !unitOriginOptions.value) return
    unitOptions.value = unitOriginOptions.value.reduce((pre, cur) => {
        if (cur.label.indexOf(state.value.unit) > -1) {
            pre.push(cur)
        }
        return pre
    }, [])
}

// 提交表单
const { isPending, mutate } = useApplySave()

// 提交
async function submit() {
    const valid = await formRef.value.formInstance.validate()
    if (valid) {
        const params = {
            id: id.value ?? '',
            ...unref(state),
            areaCode: state.value.areaCode || null, // 后端要求传null
            streetCode: state.value.streetCode || null,
            communityCode: state.value.communityCode || null,
            projectId: state.value.projectId || null,
        }
        mutate(params, {
            onSuccess: () => {
                ElMessage.success('操作成功')
                cancel()
            },
        })
    }
}

function cancel() {
    visible.value = false
    reset()
}

function reset() {
    id.value = ''
    title.value = '录入申请'
    isShowProjectId.value = false
    state.value = cloneDeep(initialState)
    formRef.value?.formInstance.resetFields()
}

const columns: PlusColumn[] = [
    {
        label: '所在区',
        prop: 'areaCode',
    },
    {
        label: '街道',
        prop: 'streetCode',
    },
    {
        label: '社区',
        prop: 'communityCode',
    },
    {
        label: '小区',
        prop: 'projectName',
    },
    {
        hideInForm: computed(() => {
            return !isShowProjectId.value
        }),
        label: '小区编码',
        prop: 'projectId',
    },
    {
        label: '栋',
        prop: 'building',
    },
    {
        label: '单元楼',
        prop: 'unit',
    },
    {
        label: '栋数',
        prop: 'num',
    },
]

const rules = computed(() => ({
    areaCode: [
        {
            message: '所在区',
            required: true,
        },
    ],
    streetCode: [
        {
            message: '街道',
            required: true

        },
    ],
    communityCode: [
        {
            message: '社区',
            required: true

        },
    ],
    projectName: [
        {
            message: '小区',
            required: true

        },
    ],
    projectId: [
        {
            message: '小区编码',
            required: true

        },
    ],
    building: [
        {
            message: '栋',
            required: true,
        },
    ],
    unit: [
        {
            message: '单元楼',
            required: true,
        },
    ],
    num: [
        {
            message: '栋数',
            required: true

        },
    ],
}))
</script>

<template>
    <el-drawer v-model="visible" :size="600" @click="clickDialog">
        <template #header>
            <div class="font-600 text-black text-24">
                {{ title }}
            </div>
        </template>
        <ElSkeleton v-if="isLoading" animated class="mt-20" />

        <template v-else>
            <div class="mt-20 plusform">
                <PlusForm ref="formRef" v-model="state" :columns="columns" :label-width="120" :rules="rules"
                    :has-footer="false" :row-props="{ gutter: 20 }">

                    <template #plus-field-areaCode>
                        <el-select v-model="state.areaCode" placeholder="请选择"
                            filterable @change="areaChange">
                            <el-option v-for="item in areaOptions" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </template>

                    <template #plus-field-streetCode>
                        <el-select v-model="state.streetCode" placeholder="请选择"
                            filterable @change="streetChange" :disabled="isStreetDisabeld">
                            <el-option v-for="item in streetOptions" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </template>

                    <template #plus-field-communityCode>
                        <el-select v-model="state.communityCode" placeholder="请选择"
                            filterable @change="communityChange" :disabled="isCommunityDisabeld">
                            <el-option v-for="item in communityOptions" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </template>

                    <template #plus-field-projectName>
                        <el-input v-model="state.projectName" clearable @click.stop="projectFocus" @input="projectInput"
                            :disabled="isProjectDisabeld" placeholder="请选择/输入">
                        </el-input>
                        <div class="positive" v-if="isProjectFocus">
                            <div class="item" v-for="(item, index) in projectOptions" :key="index"
                                @click="chooseProject(item)">
                                {{ item.label }}
                            </div>
                        </div>
                    </template>

                    <template #plus-field-building>
                        <el-input v-model="state.building" clearable @click.stop="buildingFocus" @input="buildingInput"
                            :disabled="isBuildingDisabeld" placeholder="请选择/输入">
                        </el-input>
                        <div class="positive" v-if="isBuildingFocus">
                            <div class="item" v-for="(item, index) in buildingOptions" :key="index"
                                @click="chooseBuilding(item)">
                                {{ item.label }}
                            </div>
                        </div>
                    </template>

                    <template #plus-field-unit>
                        <el-input v-model="state.unit" clearable @click.stop="unitFocus" @input="unitInput"
                            :disabled="isUnitDisabeld" placeholder="请选择/输入">
                        </el-input>
                        <div class="positive" v-if="isUnitFocus">
                            <div class="item" v-for="(item, index) in unitOptions" :key="index"
                                @click="chooseUnit(item)">
                                {{ item.label }}
                            </div>
                        </div>
                    </template>

                    <template #plus-field-num>
                        <el-input v-model="state.num"
                            oninput="if(value){value=value.replace(/[^\d]/g,'')} if(value<=0){value=''} if(value>99999){value=99999}" />
                    </template>

                </plusform>
            </div>

            <!-- <div class="mx-auto mt20 flex justify-center">
                <el-button @click="cancel">
                    取消
                </el-button>

                <SubmitBtn type="primary" :loading="isPending" @click="submit">
                    提交
                </SubmitBtn>
            </div> -->
        </template>

        <template #footer>
            <div class="flex: auto">
                <SubmitBtn type="primary" :loading="isPending" @click="submit">
                    {{ '提交' }}
                </SubmitBtn>

                <el-button @click="cancel">
                    取消
                </el-button>
            </div>
        </template>
    </el-drawer>

</template>

<style lang="scss" scoped>
.plusform {
    // height: 640px;
    overflow-y: auto;
    overflow-x: hidden;
}

.positive {
    position: absolute;
    width: 100%;
    max-height: 160px;
    background: #fff;
    z-index: 10;
    top: 34px;
    left: 0;
    overflow-y: auto;
    border: 1px solid #eee;
    border-radius: 4px;

    .item {
        padding-left: 10px;
        cursor: pointer;
    }

    .item:hover {
        background: #eee;
    }
}
</style>
